from flask import Blueprint, request
from utilsapp.mysql_con import db_pagelist, db_connect, db_delete, db_update,db_insert
from utilsapp.common import assign_value, parsing_data_id
from utilsapp import utils
import json

bluePrint = Blueprint('part', __name__)
tableName = 'part'

@bluePrint.route('/getlist', methods=["post"])
def table_list():
    device_id = assign_value(request.json, "device_id")
    sql = f'select * from part where device_id = {device_id}'
    res = db_connect(sql)
    list = []
    for item in res['data']:
        item['bearing'] = json.loads(item['bearing'])
        item['isSpeed'] = '是' if item['isSpeed'] == 1 else '否'
        item['children'] = []
        if(item['pid']) == 0:
            list.append(item)
        else:
            if item['type'] == 1 or item['type'] == 0:
                [f['children'].append(item) for f in list if f['id'] == item['pid']]
            [f['children'].append(item) for ff in list for f in ff['children'] if f['id'] == item['pid']]
    return utils.ok(list)



@bluePrint.route('/add', methods=['POST'])
def project_add():
    form = request.json['form']
    children = request.json['children']
    res = db_insert(tableName, form)
    if form['type'] != 2:
        set_speed_ratio(form['device_id'])
        return res
    else:
        pid = res['lastrowid']
        for index, child in enumerate(children):
            zhou = {
                "type": 0,
                "name": child['name'],
                "device_id": form['device_id'],
                "gearCount": None,
                "speed_ratio": 0,
                "bearing": "{}",
                "isSpeed": 0,
                "pid": pid,
            }
            res1 = db_insert(tableName, zhou)
            pid1 = res1['lastrowid']
            qu = {
                "type": 4,
                "name": "驱动轮_" + str(index + 1),
                "device_id": form['device_id'],
                "gearCount": child['qu'],
                "speed_ratio": 0,
                "bearing": "{}",
                "isSpeed": 0,
                "pid": pid1,
            }
            cong = {
                "type": 3,
                "name": "从动轮_" + str(index + 1),
                "device_id": form['device_id'],
                "gearCount": child['cong'],
                "speed_ratio": 0,
                "bearing": "{}",
                "isSpeed": 0,
                "pid": pid1,
            }
            if index == 0:
                db_insert(tableName, qu)
            elif index == len(children) - 1:
                db_insert(tableName, cong)
            else:
                db_insert(tableName, qu)
                db_insert(tableName, cong)
        set_speed_ratio(form['device_id'])
        return utils.ok({"res": 'ok'})

@bluePrint.route('/setSpeed', methods=["post"])
def set_speed():
    id = assign_value(request.json, "id")
    device_id = request.json['device_id']
    sql = f'select * from part where device_id = {device_id}'
    data = db_connect(sql)['data']
    for item in data:
        if(item['id'] != id):
            db_update(tableName,{"isSpeed": 0},f"where id =%s", {"id": item['id']})
    res = db_update(tableName,{"isSpeed": 1},f"where id =%s", {"id": id})
    set_speed_ratio(device_id)
    return res

@bluePrint.route('/delete', methods=["post"])
def table_delete():
    ids = request.json['id']
    device_id = request.json['device_id']
    for id in ids:
        res = db_delete(tableName, f'WHERE id=%s', {'id': id})
    set_speed_ratio(device_id)
    return res

def set_speed_ratio(device_id):
    sql = f'select * from part where device_id = {device_id}'
    data = db_connect(sql)['data']
    if all(item['isSpeed'] == 0 for item in data):
        return
    list = []
    for item in data:
        item['children'] = []
        if(item['pid']) == 0:
            list.append(item)
        else:
            if item['type'] == 1 or item['type'] == 0:
                [f['children'].append(item) for f in list if f['id'] == item['pid']]
            [f['children'].append(item) for ff in list for f in ff['children'] if f['id'] == item['pid']]
    speed_ratio = 1
    for index, item in enumerate(list):
        item['speed_ratio'] = speed_ratio
        if(item['type'] == 0):
            [s.update({'speed_ratio': speed_ratio}) for s in item['children']]
        else:
            for index1, item1 in enumerate(item['children']):
                if(index1 == 0):
                    item1['speed_ratio'] = speed_ratio
                    for index2, item2 in enumerate(item1['children']):
                        item2['speed_ratio'] = speed_ratio
                    speed_ratio = speed_ratio * item1['children'][0]['gearCount']
                elif(index1 == len(item['children']) - 1): 
                    speed_ratio = speed_ratio / item1['children'][0]['gearCount']
                    item1['speed_ratio'] = speed_ratio
                    for index2, item2 in enumerate(item1['children']):
                        item2['speed_ratio'] = speed_ratio
                else:
                    speed_ratio = speed_ratio / item1['children'][1]['gearCount']
                    item1['speed_ratio'] = speed_ratio
                    for index2, item2 in enumerate(item1['children']):
                        item2['speed_ratio'] = speed_ratio
                    speed_ratio = speed_ratio * item1['children'][0]['gearCount']
    if data[0]['isSpeed'] == 0:
        list1 = []
        for item in data:
            if(item['isSpeed'] == 1):
                speed_ratio = 1 / item['speed_ratio']
                item['speed_ratio'] = 1
            else:
                list1.append(item)
        for item1 in list1:
            item1['speed_ratio'] = item1['speed_ratio'] * speed_ratio
    for item in data:
        del item['children']
        db_update(tableName,item,f"where id =%s", {"id": item['id']})
        
                    




@bluePrint.route("/edit", methods=['post'])
def b():
    id_ = assign_value(request.json, "id")
    return db_update(tableName,request.json,f"where id =%s", {"id_": id_})
